package RDFManager;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class FileReader {
  private static String lastDirectory;

  public static File readFile() {

//    try {
//      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
//    } catch (UnsupportedLookAndFeelException | ClassNotFoundException | InstantiationException |
//             IllegalAccessException e) {
//      throw new RuntimeException(e);
//    }

    JFileChooser fileChooser = new JFileChooser();

    fileChooser.addChoosableFileFilter(new FileTypeFilter(".ttl", "Turtle Files(*.ttl)"));
    fileChooser.addChoosableFileFilter(new FileTypeFilter(".nt", "N-Triples Files(*.nt)"));
    fileChooser.addChoosableFileFilter(new FileTypeFilter(".rdf", "RDF/XML Files(*.rdf)"));

    loadLastDirectory();
    if (lastDirectory!=null) {
      fileChooser.setCurrentDirectory(new File(lastDirectory));
    }

    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

    int returnVal = fileChooser.showOpenDialog(null);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
      File selectedFile = fileChooser.getSelectedFile();
      System.out.println("Selected file: " + selectedFile);
      lastDirectory = selectedFile.getParent();
      saveLastDirectory();
      return selectedFile;
    } else {
      System.out.println("No file selected");
    }
    return null;
  }

  private static void saveLastDirectory() {
    try {
      Files.write(Paths.get(System.getProperty("user.dir")+"\\cache\\last_directory.txt"),lastDirectory.getBytes());
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  private static void loadLastDirectory() {
    try {
      File file = new File(System.getProperty("user.dir")+"\\cache\\last_directory.txt");
      if (file.exists()) {
        lastDirectory = new String(Files.readAllBytes(file.toPath()));
        lastDirectory = lastDirectory.trim();
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }


}
